<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const arr = [{
                id: 1,
                name: '部门1',
                pid: 0
            },
            {
                id: 2,
                name: '部门2',
                pid: 1
            },
            {
                id: 3,
                name: '部门2',
                pid: 1
            },
            {
                id: 4,
                name: '部门3',
                pid: 3
            },
            {
                id: 5,
                name: '部门4',
                pid: 4
            },
        ]

        function toTree(arr)
        {
            let result = [];
            let map = new Map();
            arr.forEach(item=>{
                map.set(item.id,{...item,vchildren:[]});
            })
            
            arr.forEach(item=>{
                let node = map.get(item.id);
                if(!map.has(node.id-1))
                {
                   result.push(node);
                }
                else
                {
                    let parentNode = map.get(node.id-1);
                    parentNode.vchildren.push(node);
                }
            })

            return result;
        }

        let result = toTree(arr);
        console.log(result);
        console.log(JSON.stringify(result));
    </script>
</body>

</html>